<template>
  <div class="relative">
    <div class="flex flex-col">
      <div :style="{ height: tableHeight + 'px' }" class="border-bottom">
        <div>式样</div>
        <div>车号</div>
        <div>车辆型号</div>
        <div>车辆代号</div>
        <div>VIN</div>
        <div>ENG</div>
        <div>轮胎规格</div>
      </div>
      <div>
        <div v-for="day in dateList" :key="day" class="border-bottom" :class="[`h-${initHeight}px`, `line-height-${initHeight}px`]">{{
          dayjs(day).format('MM-DD')
        }}</div>
      </div>
    </div>
    <div class="flex absolute top-0 left-100px h-100%">
      <div class="container relative" v-for="(item, itemI) in list" :key="item.id">
        <div :style="{ height: tableHeight + 'px' }">
          <div>{{ item.sy }}</div>
          <div>{{ item.ch }}</div>
          <div>{{ item.xh }}</div>
          <div>{{ item.dh }}</div>
          <div>{{ item.vin }}</div>
          <div>{{ item.eng }}</div>
          <div>{{ item.gg }}</div>
        </div>
        <Vue3DraggableResizable
          v-for="(el, elI) in item.children"
          :initW="110"
          :initH="el.height"
          :minH="40"
          v-model:x="draggableX"
          v-model:y="el.y"
          v-model:w="draggableW"
          v-model:h="el.height"
          v-model:active="el.active"
          :disabledX="true"
          :disabledW="true"
          :parent="true"
          :draggable="true"
          :resizable="true"
          :handles="['bm']"
          @activated="activatedHandle(itemI, elI)"
          @drag-end="dragEndHandle"
          @resize-end="resizeEndHandle"
          :style="{ zIndex: zIndex }"
          class="draggable-div"
        >
          <a-tooltip placement="rightTop">
            <template #title>
              <span>{{ el.title }}</span>
            </template>
            <div style="height: 100%" class="truncate">
              <span>{{ el.title }}</span>
            </div>
          </a-tooltip>
          <EditFilled @click.stop="handleViewRemark(el)" class="absolute top-0 right--25px cursor-pointer" title="备注"/>
          <InfoCircleFilled class="absolute top-0 right-0 color-red "/>
        </Vue3DraggableResizable>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, inject } from 'vue';
  import Vue3DraggableResizable from 'vue3-draggable-resizable';
  import 'vue3-draggable-resizable/dist/Vue3DraggableResizable.css';
import { Modal } from 'ant-design-vue';
  import {
    EditFilled,
    InfoCircleFilled
} from '@ant-design/icons-vue';
  const list = ref([]);
  const dayjs: any = inject('$dayjs');
  let planStartDate = '2023-04-01';
  const planEndDate = dayjs('2023-10-31');

  const itemI = ref(0);
  const elI = ref(0);
  const draggableX = 50;
  const draggableW = 100;
  // 初始高度
  const initHeight = ref(40);
  const tableHeight = 180;
  const zIndex = ref(0);

  const dateList: string[] = [];

  // 获取两个日期之间的所有日期，包括起始和结束日期
  handleMonthlyDates();
  function handleMonthlyDates() {
    let startDate = dayjs(planStartDate);
    while (startDate.isBefore(planEndDate) || startDate.isSame(planEndDate, 'day')) {
      dateList.push(startDate.format('YYYY-MM-DD'));
      startDate = startDate.add(1, 'day');
    }
  }

  // 计算两个日期之间的天数差
  const diffDay = (start: string, end: string) => {
    const startDate = dayjs(start);
    const endDate = dayjs(end);
    const daysDifference = endDate.diff(startDate, 'day') + 1;
    return daysDifference;
  };

  // 通过天数计算某个日期的
  const diffDate = (date, duration) =>{
    return dayjs(date).add(duration, 'day').format('YYYY-MM-DD');
  }

  handleData();
  function handleData() {
    const res = [
      {
        id: 3,
        sy: '汽油国6M15B',
        xh: 'TV7156NM',
        dh: 'MZEA11L-GEFNZC',
        ch: 'E301',
        vin: 'LFMAL1CC8K0000027',
        eng: '0000157',
        gg: '195/65R15',
        children: [
          {
            sd: '2023-04-08',
            ed: '2023-04-08',
            title: 'MT试验ECU改写（FTRD）',
          },
          {
            sd: '2023-04-11',
            ed: '2023-04-12',
            title: '排放初期确认@FTRD',
          },
          {
            sd: '2023-04-13',
            ed: '2023-04-13',
            title: '天津运输',
          },
          {
            sd: '2023-04-14',
            ed: '2023-04-20',
            title: '5000km磨合',
          },
          {
            sd: '2023-04-24',
            ed: '2023-04-28',
            title: '油耗（NEDC）如果E302结果合格，试验取消',
          },
          {
            sd: '2023-04-21',
            ed: '2023-04-21',
            title: 'MT试验ECU改写（CATARC）',
          },
          {
            sd: '2023-04-31',
            ed: '2023-05-04',
            title: '26（卤素高1）、27（卤素高）、后视镜安装、除霜、除雾、刮水器、外廓尺寸、60、油箱安装、99',
          },
          {
            sd: '2023-05-07',
            ed: '2023-05-11',
            title: 'EMC(GB 34660)、ABS EMC',
          },
          {
            sd: '2023-05-12',
            ed: '2023-05-13',
            title: '盐城运输',
          },
          {
            sd: '2023-05-14',
            ed: '2023-05-18',
            title: '制动、ABS、加速噪声、定置噪声',
          },
          {
            sd: '2023-05-19',
            ed: '2023-05-20',
            title: '天津运输',
          },
        ],
      },
      {
        id: 1,
        sy: '汽油国6M15B',
        xh: 'TV7156NM',
        dh: 'MZEA11L-GEFNZC',
        ch: 'E302',
        vin: 'LFMAL1CC5K0000017',
        eng: '0000158',
        gg: '195/65R15',
        children: [
          {
            sd: '2023-04-09',
            ed: '2023-04-10',
            title: '排放初期确认@FTRD',
          },
          {
            sd: '2023-04-08',
            ed: '2023-04-08',
            title: 'MT试验ECU改写（FTRD）',
          },
          {
            sd: '2023-04-11',
            ed: '2023-04-11',
            title: '天津运输',
          },
        ],
      },
      {
        id: 2,
        sy: '汽油国6M15B',
        xh: 'TV7156N',
        dh: 'MZEA11L-GEXNBC',
        ch: 'E303',
        vin: 'LFMAL1CC7K0000018',
        eng: '0000159',
        gg: '205/55R16',
        children: [
          {
            sd: '2023-04-08',
            ed: '2023-04-08',
            title: 'MT试验ECU改写（FTRD）',
          },
          {
            sd: '2023-04-09',
            ed: '2023-04-10',
            title: '排放初期确认@FTRD',
          },
          {
            sd: '2023-04-11',
            ed: '2023-04-11',
            title: '天津运输',
          },
        ],
      },
      {
        id: 3,
        sy: '汽油国6M15B',
        xh: 'TV7156N',
        dh: 'MZEA11L-GEXNBC',
        ch: 'E303',
        vin: 'LFMAL1CC7K0000018',
        eng: '0000159',
        gg: '205/55R16',
        children: [
          {
            sd: '2023-04-08',
            ed: '2023-04-08',
            title: 'MT试验ECU改写（FTRD）',
          },
          {
            sd: '2023-04-09',
            ed: '2023-04-10',
            title: '排放初期确认@FTRD',
          },
          {
            sd: '2023-04-11',
            ed: '2023-04-11',
            title: '天津运输',
          },
        ],
      },
    ];
    res.forEach((item) => {
      item.children.forEach((childItem) => {
        Object.assign(childItem, {
          startDate: childItem.sd,
          endDate: childItem.ed,
          active: false,
          duration: diffDay(childItem.sd, childItem.ed),
          height: diffDay(childItem.sd, childItem.ed) * initHeight.value,
          y: diffDay(planStartDate, childItem.sd) * initHeight.value - initHeight.value + tableHeight,
        });
      });
    });
    list.value = res;
  }

  // 查看备注信息
  function handleViewRemark (data) {
    console.log(data);
      Modal.info({
      title:  "备注信息",
      content:data.title,
      onOk() {
        console.log('ok');
      },
    });
    
  }

  // 点击任务
  function activatedHandle(itemI1, elI1) {
    itemI.value = itemI1;
    elI.value = elI1;
    zIndex.value = 11;
  }

  // 改变任务高度结束后
  function resizeEndHandle({ x, y, w, h }) {
    // 拖动后的高度除初始高度，获得天数
    let duration = Math.round(h / initHeight.value);
    if (duration <= 0) duration = 1;
    handleListChildrenData('height', duration * initHeight.value);
    handleListChildrenData('duration', duration);
    const { sd } = list.value[itemI.value].children[elI.value];
    const newEndDate = diffDate(sd, duration - 1);
    handleListChildrenData('ed', newEndDate);
    console.log(list.value[itemI.value].children[elI.value]);
  }

  // 拖动任务结束后
  function dragEndHandle({ x, y }) {
    // 距离顶部高度
    const distanceTopHeight = Math.round((y - tableHeight) / initHeight.value) * initHeight.value + tableHeight;
    if ((y - tableHeight) % initHeight.value != 0) {
      handleListChildrenData('y', distanceTopHeight);
    }
    if ((y - tableHeight) % initHeight.value < 0) {
      handleListChildrenData('y', tableHeight);
    }
    // 计算距离计划开始日期天数
    let distancePlanStartDate = (distanceTopHeight - tableHeight) / initHeight.value;
    distancePlanStartDate = distancePlanStartDate > 0 ? distancePlanStartDate : 0;
    if (distancePlanStartDate >= 0 ) {
      const newSd = diffDate(planStartDate, distancePlanStartDate);
      handleListChildrenData('sd', newSd);
      const duration = list.value[itemI.value].children[elI.value].duration;
      const newEd = diffDate(newSd, duration - 1);
      handleListChildrenData('ed', newEd);
    }

    console.log(list.value[itemI.value].children[elI.value]);
  }

  function handleListChildrenData(key, value) {
    list.value[itemI.value].children[elI.value][key] = value;
  }
</script>
<style scoped lang="less">
.border-bottom{
  border-bottom:1px solid #ccc;
}
  .container {
    width: 200px;
    height: 100%;
    border-right: 1px solid #ccc;
    .draggable-div {
      background-color: lightblue;
      cursor: move;
    }
  }
</style>
